import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { deleteAddressAPI, addAddressAPI, fetchAddressListAPI, findAddressDetailAPI, editAddressAPI } from "@/api/addressApi.ts";
import type { Address } from "@/types/addressTypes";
import type { Ref } from "vue";

const useAddressStore = defineStore("addressStore", () => {
    /*地址列表*/
    const addressList: Ref<Address[]> = ref<Address[]>([]);
    /*控制弹出层的显示*/
    const showPopup: Ref<boolean> = ref<boolean>(false);
    /*控制编辑模式*/
    const edit: Ref<boolean> = ref<boolean>(false);
    /*第一个收货地址*/
    const address = computed<Address>(() => addressList.value[0]);

    /*获取地址列表的请求函数*/
    const fetchAddressList = async (): Promise<void> => {
        const { data }: { data: Address[] } = await fetchAddressListAPI();
        addressList.value = data;
    };
    /*添加地址的请求函数*/
    const addAddress = async (data: Address): Promise<void> => {
        await addAddressAPI(data);
    };
    /*删除地址的请求函数*/
    const deleteAddress = async (addressId: string): Promise<void> => {
        await deleteAddressAPI(addressId);
    };
    /*查找地址的请求函数*/
    const findAddressDetail = async (addressId: string): Promise<Address> => {
        const { data }: { data: Address } = await findAddressDetailAPI(addressId);
        return data;
    };
    /*编辑地址的请求函数*/
    const editAddress = async (addressId: string, data: Address): Promise<void> => {
        await editAddressAPI(addressId, data);
    };

    const changeShowPopup = (flag: boolean): void => {
        showPopup.value = flag;
    };

    const changeEdit = (flag: boolean): void => {
        edit.value = flag;
    };

    return {
        addressList,
        showPopup,
        edit,
        address,
        changeShowPopup,
        changeEdit,
        fetchAddressList,
        addAddress,
        deleteAddress,
        findAddressDetail,
        editAddress,
    };

});


export default useAddressStore;
